function [schidx,nsidx] = ToneEdgeDetection(sch,schidx)
% [schidx,nsidx] = ToneEdgeDetection(sch,schidx)
%
%   Paradigm consists of slowly rising and falling tones.
%
%   Trial Types:
%       0 ... quiet -> tone
%       1 ... catch trial (stimulus based on last trial type)
%       2 ... tone  -> quiet

%  Takes the schedule and schidx as input.
%       SCH is the schedule structure
%       SCHIDX is a 1D matrix with the number of rows equal to the number
%           of unique trials; i.e. size(trials,1).
%  Returns an updated version of SCHIDX and NSIDX
%       NSIDX is the next schedule trial index, i.e. the next index
%           selected from the SCH.trials matrix to run.
%       SCHIDX should be updated with the number of runs for each unique
%           trial in SCH.trials.  The returned version should have
%           SCHIDX(NSIDX) incremented.
%
%  This same format for input and output paramters must be met for custom
%  trial select functions (i.e., experiment.trialselectfcn);
%
%  DJS (c) 2011

global G_RP

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CATCH_P = 0; % probability of catch trial

if ~isfield(sch,'trial_idx'), sch.trial_idx = 1; end
trials   = sch.trials;
respvals = sch.response_vals;
boxid    = sch.boxid;

% find some paramters
fwidx = findincell(strfind(sch.writeparams,'FreqList'));
cbidx = findincell(strfind(sch.writeparams,'ToneCalibration'));
lvidx = findincell(strfind(sch.writeparams,'ToneDB'));

fridx = findincell(strfind(sch.readparams, 'ToneFreq'))  + 1;
ttidx = findincell(strfind(sch.readparams, 'trial_type'))+ 1;
lridx = findincell(strfind(sch.readparams, 'ToneDB'))    + 1;

flist = cell2mat(trials(:,fwidx)); % frequency list
llist = cell2mat(trials(:,lvidx)); % level list
clist = cell2mat(trials(:,cbidx)); % calibration list

% which module?
writemod = sch.writemodule(fwidx);
RP = G_RP(writemod);

% initialize first trial
if isempty(respvals)
    schidx = zeros(size(trials,1),1); % initialize SCHIDX
    r = randperm(length(schidx));
    nsidx = r(1);
    schidx(nsidx) = 1;
    
    RP.SetTagVal(sprintf('trial_type~%d',     boxid),0);
    RP.SetTagVal(sprintf('ToneFreq~%d',       boxid),flist(nsidx));
    RP.SetTagVal(sprintf('ToneDB~%d',         boxid),llist(nsidx));
    RP.SetTagVal(sprintf('ToneCalibration~%d',boxid),clist(nsidx));
    
    fprintf('QUIET -> TONE (%d Hz @ %ddB)\n', ...
        trials{nsidx,fwidx},trials{nsidx,lvidx})

    return
end

% default NSIDX is same as previous trial
nsidx = find(flist == respvals(end,fridx) & llist == respvals(end,lridx),1,'last');

% last trial type
lasttt = respvals(end,ttidx);
switch lasttt
    case 0 % quiet -> tone
        tt = rand(1) < CATCH_P; % Test if catch trial
        if ~tt, tt = 2; end % if next trial is not catch trial then must be tone -> quiet

    case 2 % tone  -> quiet
        tt = rand(1) < CATCH_P; % Test if catch trial
        if ~tt
            tt = 0; % if next trial is not catch trial then must be quiet -> tone
            % pick new frequency giving priority to least chosen
            i = find(schidx == min(schidx));
            r = randperm(length(i));
            nsidx = i(r(1));            
        end
        
    case 1 % catch trial
        if respvals(end-1,ttidx) == 0
            tt = 2; % tone -> quiet

        else
            tt = 0; % quiet -> tone
            % pick new frequency giving priority to least chosen
            i = find(schidx == min(schidx));
            r = randperm(length(i));
            nsidx = i(r(1));

        end     
end

%%%%%%%%% vvvv TESTING vvvv 
switch tt
    case 0
        fprintf('QUIET -> TONE (%d Hz @ %ddB)\n', ...
            trials{nsidx,fwidx},trials{nsidx,lvidx})

    case 2
        fprintf('TONE (%d Hz @ %ddB) -> QUIET\n', ...
            trials{nsidx,fwidx},trials{nsidx,lvidx})
    case 1
        fprintf('CATCH TRIAL\n')
        
end
%%%%%%%%% ^^^^ TESTING ^^^^ 


RP.SetTagVal(sprintf('trial_type~%d',boxid),tt);

if tt == 0 % quiet -> tone, update stimulus parameters
    while RP.GetTagVal(sprintf('stim_state~%d',boxid)); end 
    RP.SetTagVal(sprintf('ToneFreq~%d',boxid),       flist(nsidx));
    RP.SetTagVal(sprintf('ToneCalibration~%d',boxid),clist(nsidx));
    RP.SetTagVal(sprintf('ToneDB~%d',boxid),         llist(nsidx));
    schidx(nsidx) = schidx(nsidx) + 1;
end










